from socketserver import BaseRequestHandler, TCPServer, ThreadingTCPServer, BaseServer
from threading import Thread
import zmq
import configparser
import os
import json
import time

class myconf(configparser.ConfigParser):
    def optionxform(self, optionstr):
        return optionstr

class EchoHandler(BaseRequestHandler):
    def handle(self):
        print('socket来源IP和端口：', self.client_address)
        source_ip = self.client_address[0]
        source_port = self.client_address[1]
        self.thread_communication(source_ip)
        
    def thread_communication(self, source_ip):
        context = zmq.Context()
        global config
        config_file = r'D:\pycharms\django\operationsb\update\tools\config.ini'
        config = myconf()
        config.read(config_file)
        thread_socket_host = config.get('update','server_ip')
        thread_socket_post1 = config.get('update','thread_req1_port')
        thread_socket_post2 = config.get('update', 'thread_req2_port')

        #thread_logo = config.get('ports','thread_logo_1')
        thread_socket = context.socket(zmq.REQ)
        thread_socket.connect("tcp://%s:%s" % (thread_socket_host, thread_socket_post1))
        thread_socket.send_string(source_ip)
        print('已经发送消息')
        msg = thread_socket.recv_string()
        endmsg = self.send_zip(json.loads(msg))
        thread_socket.close()
        
        thread_socket_2 = context.socket(zmq.REQ)
        thread_socket_2.connect("tcp://%s:%s" % (thread_socket_host, thread_socket_post2))
        thread_socket_2.send_string(endmsg)
        thread_socket_2.close()
        context.term()
    
    def send_zip(self,return_zcell_json):
        global Equipment
        Equipment_file = r'D:\pycharms\django\operationsb\update\tools\Equipment.ini'
        Equipment = myconf()
        Equipment.read(Equipment_file)
        zcell_name = ''
        while True:
            msg = self.request.recv(7)
            if not msg:
                break
            else:
                zcell_name = msg.decode('utf-8')
                status = 0
                for single_zcell_json in return_zcell_json:
                    if single_zcell_json["id"] == zcell_name:
                        for i in single_zcell_json["module"]:
                            status = 1
                            if i.endswith('zip'):
                                self.read_zip(i,1)
                            else:
                                self.read_zip(i,2)
                        self.request.send(b'1')
                        break
                if status == 0:
                    print("接收到的zcell名称与匹配更新的不一致")
                    zcell_name = 'error'
                    break
                break
        return zcell_name
    
    def read_zip(self,module_zip,status):
        page_file = config.get('service_side', 'updata_file')
        f2 = ''
        zip_module = ''
        if status == 1:
            print('更新全部')
            zip_module = module_zip
            zip_name = zip_module.split('.')
            zip_file = Equipment.get("Equipment2", zip_name[0])
            f1 = os.path.join(page_file, zip_file)
            f2 = os.path.join(f1, zip_module)
        elif status == 2:
            print('单独更新')
            module_name = module_zip[:-5] + ".zip"
            zip_file = Equipment.get("Equipment2", module_zip[:-5])
            zip_module = module_name + "|" + module_zip
            f1 = os.path.join(page_file, zip_file)
            f2 = os.path.join(f1, module_name)
            print('发送数据包: %s' % zip_module)
            print('压缩包路径：%s' % f2)
        self.request.send(bytes(str(len(zip_module)), encoding="utf8"))
        self.request.send(bytes(zip_module, encoding="utf8"))
        with open(f2, 'rb') as e:
            for data in e:
                self.request.send(data)
        e.close()
        time.sleep(5)
        self.request.send(b'next')
#
#
# if __name__ == '__main__':
#     NWORKERS = 1
#     serv = TCPServer(('', 20000), EchoHandler)
#     for n in range(NWORKERS):
#         t = Thread(target=serv.serve_forever)
#         t.daemon = True
#         t.start()
#     serv.serve_forever()
#

